const {
	Backend,
	Joi
} = require('dx-router-admin');
const _ = require('underscore');
module.exports = class Company extends Backend {
	constructor(ctx) {
		super(ctx);
		this.multiFields = ['demand', 'usehunt', 'needed','parter'];
		//this.indexWith = ['parent','bestobj','childrens'];
		//
		// this.dto = {
		// 	menu_id: Joi.string().required().error(new Error('菜单标识不能为空')),
		// 	name: Joi.string().required().error(new Error('菜单名称不能为空')),
		// 	enable: Joi.boolean().required().error(new Error('状态类型不正确')),
		// };
	}
	async index(param) {
		let response;
		const time = new Date().getTime();
		if (param._id) {
			const list = await this.currentService.with(this.indexWith).where({_id:param._id}).select();
			response = {
				data: {
					list,
					total: list.length
				},
				code: 1000
			}
		} else {
			response = await super.index(param);
			const talent_ids = [];
			const company_ids = [];
			const parent_ids = [];
			response.data.list.forEach(company=>{
				company.parent_id&&company_ids.push(company.parent_id);
				company.best_link&&talent_ids.push(company.best_link);
				parent_ids.push(company._id);
			});
			/************************************/
			let talents,companys,childrens;
			if(talent_ids.length){
				talents = await this.$dx.service.talent.findByIds(talent_ids);
			}
			if(company_ids.length){
				companys = await this.currentService.findByIds(company_ids);
			}
			response.data.list.forEach(company=>{
				if(company.parent_id){
					const parent = _.findWhere(companys,{_id:company.parent_id});
					parent&&(company.parentCompany = parent.name); 
				}
				if(company.best_link){
					const talent = _.findWhere(talents,{_id:company.best_link});
					talent&&(company.bestobj = talent); 
				}
			});
			/************************************/
			/************************************/
			childrens = await this.currentService.where({'parent_id':['in',parent_ids]}).limit(1000).select();
			if(childrens.length){
				childrens.forEach(child=>{
					const company = _.findWhere(response.data.list,{_id:child.parent_id}); 
					if(company.childrens) {
						company.childrens.push({
							_id:child._id,
							name:child.name
						})
					}else{
						company.childrens = [{
							_id:child._id,
							name:child.name
						}];
					}
				})
			}
			/************************************/
			
		}
		response.data.list = await this.$dx.service.talent.loadTalentList('hrlist',response.data.list);
		response.data.list = await this.currentService.loadTargetCompanyList('target_company',response.data.list);
		//console.error('客户时间差：',new Date().getTime() - time)
		return response;
	}
	async edit(param){
		const children = [];
		if(param.children){
			children.push(...param.children);
		}
		delete param.children;
		const result = await super.edit(param);
		await this.currentService.dealChildren({_id:param._id,children});
		return result
	}
	async add(param){
		const children = [];
		if(param.children){
			children.push(...param.children);
		}
		delete param.children;
		const result = await super.add(param);
		if(result.data&&children.length){
			await this.currentService.dealChildren({_id:result.data,children})
		}
		return result;
	}
	findByIds(param){
		return this.currentService.findByIds(param._ids||[]);
	}
	async addSimple(param){
		const result = await this.currentService.findByName(param.name);
		if(result){
			return this.$dx.error('公司名称已存在',result);
		}
		return await super.add(param)
	}
	async select({_ids}){
		const list = await this.currentService.with(['parent']).where({_id:['in',_ids]}).select();
		const list2 = await this.$dx.service.talent.loadTalentList('hrlist',list)
		const list3 = await this.$dx.service.tags.loadTagList('product',list2);
		return list3;
	}
	async merge(param){
		/*************** 保存合并前的公司 id****************************/
		const merge_list = await this.currentService.where({_id:['in',param._ids]}).field('merge_ids').select();
		let merge_ids = [];
		_.each(merge_list,company=>{
			if(Array.isArray(company.merge_ids)){
				merge_ids.push(...company.merge_ids);
			}
		})
		merge_ids.push(...param._ids);
		/*******************获取要修改的企业 _id*************************************/
		let maxCount = 0,new_id;
		for(let i = 0;i<param._ids.length;i++){
			const count = await this.$dx.service.talent.where({company_id:param._ids[i]}).count();
			if(count>maxCount){
				new_id = param._ids[i];
				maxCount = count;
			}
		}
		if(new_id){
			merge_ids = _.without(_.uniq(merge_ids),new_id);
			param._ids = _.without(param._ids,new_id);
			await this.currentService.where({_id:new_id}).update({...param.merge,merge_ids})
			//await super.add({...param.merge,merge_ids:_.uniq(merge_ids)})
		}else{
			const result = await super.add({...param.merge,merge_ids:_.uniq(merge_ids)});
			new_id = result.data;
		}
		/***********************************/
		/***********************************************/
		//const result = await super.add({...param.merge,merge_ids:_.uniq(merge_ids)});
		const result2 = await super.del({ids:param._ids});
		if(result2.code==1000){
			await this.updateCMerge({_id:new_id,_ids:param._ids});
			return this.$dx.success('客户合并成功，关联信息后台处理中',new_id);
		}else{
			return result2
		}
	}
	/*
	* 合并公司后处理原有公司指向
	* 
	*/
	async updateCMerge(param){
		await this.$dx.service.candidate.updateMerge(param);// 项目候选人公司合并
		await this.$dx.service.project.updateMerge(param);// 项目合并
		await this.currentService.updateCMerge(param);//公司对标合并
		await this.$dx.service.job.updateCMerge(param);// 职位所属公司合并
		return this.$dx.service.talent.updateCMerge(param);//简历对应公司合并
	}
	async get(param){
		const data = await this.currentService.with(['parent','bestobj','childrens']).where('_id',param._id).find();
		if(!_.isEmpty(data.hrlist)){
			data.hrlists = await this.$dx.service.talent.findByIds(data.hrlist);
		}
		if(!_.isEmpty(data.product)){
			data.products = await this.$dx.service.picture.findByIds(data.product);
		}
		if(!_.isEmpty(data.target_company)){
			data.target_companys = await this.currentService.findByIds(data.target_company);
		}
	    return this.$dx.success('查询成功',data);
	}
	
};